package cn.xorange.commons.datasource.service;

import cn.hutool.core.util.ReflectUtil;
import com.alibaba.druid.pool.DruidDataSource;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * @author yangjian
 */
public class TransactionChooseFactory {

    /**
    public Object chooseTransactionDatasource(String transaction, String dsName, Map<String,Object> dataSource){
        // 创建DruidXADataSource数据源
        // 采用DruidXADataSource而不是DruidDataSource因为DruidXADataSource支持分布式
//        if (StringUtil.equals(transaction,"jta")){
//            return this.jtaTransaction(dsName,dataSource);
//        }else {
//            return this.seataTransaction(dataSource);
//        }
        return this.seataTransaction(dataSource);
    }

//    private DruidXADataSource jtaTransaction(String dsName, Map<String,Object> dataSource){
//        DruidXADataSource druidXADataSource = new DruidXADataSource();
//        Field[] myDataSourceFields = ReflectUtil.getFields(druidXADataSource.getClass());
//        for(Field field : myDataSourceFields){
//            String n = field.getName();
//            if(dataSource.hasKey(n)){
//                ReflectUtil.setFieldValue(druidXADataSource,n,dataSource.get(n));
//            }
//        }
//
//        AtomikosDataSourceBean sourceBean = new AtomikosDataSourceBean();
//        // 必须为数据源指定唯一标识
//        sourceBean.setUniqueResourceName(dsName);
//        sourceBean.setXaDataSource(druidXADataSource);
//        //sourceBean.setXaProperties(xaProperties);
//        return druidXADataSource;
//    }
*/
    public DruidDataSource seataTransaction(Map<String,Object> dataSource){
        DruidDataSource druidDataSource = new DruidDataSource();
        Field[] myDataSourceFields = ReflectUtil.getFields(druidDataSource.getClass());
        for(Field field : myDataSourceFields){
            String n = field.getName();
            if(dataSource.containsKey(n)){
                ReflectUtil.setFieldValue(druidDataSource,n,dataSource.get(n));
            }
        }
        return druidDataSource;
    }
}
